package com.longxi.tianjintianbao.ui.presenter.main;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.widget.Toast;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataPatrolController;
import com.longxi.tianjintianbao.greedao.controller.DataWorkController;
import com.longxi.tianjintianbao.greedao.entity.Work;
import com.longxi.tianjintianbao.listener.AdapterListener;
import com.longxi.tianjintianbao.model.work.News;
import com.longxi.tianjintianbao.model.message.MessageCount;
import com.longxi.tianjintianbao.model.work.NewsList;
import com.longxi.tianjintianbao.ui.activity.main.MainActivity;
import com.longxi.tianjintianbao.ui.activity.news.NewDetailActivity;
import com.longxi.tianjintianbao.ui.adapter.multitype.LabelViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.work.NewViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.work.WorkViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.base.LazyFragment;
import com.longxi.tianjintianbao.ui.view.main.IHomeFgView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NetUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class HomeFgPresenter extends BasePresenter<IHomeFgView> {

    private MultiTypeAdapter adapter;
    private Items items;
    private int SPAN_COUNT = 4;
    private Intent intent = new Intent();
    private boolean isRefresh = false;//页面判断是否要刷新

    public HomeFgPresenter(BaseActivity context, LazyFragment fragment) {
        super(context, fragment);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(String.class, new LabelViewBinder());
            adapter.register(NewsList.class, new NewViewBinder(listener));
            adapter.register(Work.class, new WorkViewBinder(listener));
            final GridLayoutManager layoutManager = new GridLayoutManager(mContext, SPAN_COUNT);
            GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    Object item = items.get(position);
                    if (item instanceof String) {
                        return 4;
                    }
                    if (item instanceof Work) {
                        return 1;
                    }
                    return SPAN_COUNT;
                }
            };
            layoutManager.setSpanSizeLookup(spanSizeLookup);
            getView().getRvContent().setLayoutManager(layoutManager);
            getView().getRvContent().setAdapter(adapter);
        }
    }

    //设置首页功能模块
    public void setData(){
        if(NetUtils.isNetworkAvailable(mContext)){
            setNetworkingModeData();
        }else{
            setOfflineData();
        }
    }

    /**
     * 联网首页数据
     */
    public void setNetworkingModeData(){
        items = new Items();
        items.addAll(DataWorkController.findWorkCategoryVisible(1));

        //工作模块
        int count = (int)DataPatrolController.isUploadData();//巡检数量
        DataWorkController.updateWorkMessage(17, count);
        List<Work> gonzuo = DataWorkController.findWorkCategoryVisible(2);
        if(gonzuo.size() > 0){
            items.add("工作");
        }
        items.addAll(gonzuo);

        List<News> news = new ArrayList<>();
        news.add(new News("通知: 欢迎使用" + MyUtils.getString(R.string.app_name)));
        news.add(new News("通知: 欢迎使用" + MyUtils.getString(R.string.app_name)));
        items.add(new NewsList(news));

        List<Work> atwo = DataWorkController.findWorkCategoryVisible(3);
        if(atwo.size() > 0){
            items.add("@我");
        }
        items.addAll(atwo);

        adapter.setItems(items);
        adapter.notifyDataSetChanged();
        mFragment.hideLoading();
    }

    /**
     * 离线首页数据
     */
    public void setOfflineData(){
//        items = new Items();
//        items.add("工作(离线功能)");
//        int count = (int)DataPatrolController.isUploadData();//巡检内容
//        items.add(new Work(3, R.mipmap.ic_home_inspection,count , R.string.xj, PatrolListActivity.class));
//        adapter.setItems(items);
//        adapter.notifyDataSetChanged();
//        mFragment.hideLoading();

    }

    /**
     * 获取信息个数
     */
    public void getMessageCount() {
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("type", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().getMessageCount(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<MessageCount>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                if(getView().getRefreshLayout() != null && getView().getRefreshLayout().isRefreshing()){
                    getView().getRefreshLayout().finishRefresh();//传入false表示刷新失败
                }
            }

            @Override
            public void onNext(HttpResult<MessageCount> result) {
                if(getView().getRefreshLayout() != null && getView().getRefreshLayout().isRefreshing()){
                    getView().getRefreshLayout().finishRefresh();//传入false表示刷新失败
                }
                if(result.getCode() != 0){
                    return;
                }
                if(result.getData().size() == 0){
                    return;
                }
                for (int i = 0; i < result.getData().size(); i++) {
                    DataWorkController.updateWorkMessage(result.getData().get(i).getType(), result.getData().get(i).getCount());
                }

                intent.setAction(AppConst.REFRESH_HOME_FRAGMENT);
                mContext.sendBroadcast(intent);

//                setNetworkingModeData();
            }
        });
    }

    AdapterListener listener = new AdapterListener() {
        @Override
        public void onClick(int position) {
            MainActivity mainActivity = (MainActivity) mContext;
            if(items.get(position) instanceof NewsList){
                MyUtils.showToast("欢迎使用" + MyUtils.getString(R.string.app_name));
                mContext.jumpToActivity(NewDetailActivity.class);
            }
            if(items.get(position) instanceof Work){
                Work work = (Work) items.get(position);
                mainActivity.showShowBtn(AppConst.mTitle[new Long(work.getId()).intValue() - 1]);
            }
        }

        @Override
        public void onDelete(int position) {

        }
    };

    public void onDestroy() {
        listener = null;
        NewViewBinder.instance().onDestroy();
    }

    public void setRefresh(boolean refresh) {
        isRefresh = refresh;
    }

    public void onResume() {
        if(isRefresh){
            setRefresh(false);
            getMessageCount();
        }
//        NewViewBinder.instance().onResume();
    }

    public void onPause() {
//        NewViewBinder.instance().onPause();
    }
}
